package in.abip.kazumi;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.Socket;

import android.util.Log;

public class TelnetClient {
	private Socket _socket = null;
	private BufferedReader _bufferedReader = null;
	private BufferedWriter _bufferedWriter = null;
	
	public Boolean connect(String host, int port) {
		try {
			InetSocketAddress address = new InetSocketAddress(host, port);
			_socket = new Socket();
			_socket.connect(address, 100);
			_socket.setKeepAlive(true);
			_bufferedWriter = new BufferedWriter(new OutputStreamWriter(
					_socket.getOutputStream()), 1024);
			_bufferedReader = new BufferedReader(new InputStreamReader(
					_socket.getInputStream()), 1024);
//			int rst = 0;
//			while (rst != 1) {
//				try {
//					rst = _bufferedReader.read();
//				} catch (IOException e) {
//					rst = 1;
//				}
//			}
		} catch (IOException e) {
			Log.d("debug", "Could not connect");
			return false;
		}
		Log.d("debug", "Connected");
		return true;
	}

	public void disconnect() {
		try {
			_socket.close();
		} catch (IOException e) {}
	}

	public String attention(String command) {
//		Log.d("debug", command);
		String result;
		try {
			_bufferedWriter.write(command + "\r", 0, command.length() + 1);
			_bufferedWriter.flush();
		} catch (IOException e) {
			return null;
		}
		try {
			Log.d("debug", "Reading");
			result = _bufferedReader.readLine();
			Log.d("debug", result);
			return result;
		} catch (Exception e) {
//			Log.d("debug", "exception");
			return null;
		}
	}
}
